﻿using System;
using System.Collections.Generic;
using System.Text;
using RS.DOM.Common;

namespace RS.DOM.Types
{
    public class Name: Token
    {
        public Name(Context context, string text)
            : base(context)
        {
            base.Text = text;
            base.TokenType = TokenType.Name;
        }

        public override Token Resolve()
        {
            Token token = this.Context.Document.GetVariable(base.Text);
            if (token != null)
            {
                token.PrevToken = this.PrevToken;
                token.NextToken = this.NextToken;
                return token;
            }
            else
            {
                return this;
            }
        }

        public override Token Operation(Token token, OperationType type)
        {
            Token result = null;

            if (type == OperationType.Apply ||
                type == OperationType.Add ||
                type == OperationType.PlusApply)
            {
                result = token;
            }
            else if (type == OperationType.AddApply)
            {
                Collection sc = new Collection(this.Context);
                sc.Result.Add(token);
                result = sc;
            }
            else
            {
                throw new Exception("Name " + base.Text + " doesn't resolved.");
            }

            this.Context.Document.AddVariable(base.Text, result.Copy());
            
            return result;
        }

        public override Token Create()
        {
            return new Name(this.Context, this.Text);
        }
    }
}
